//
//  HomeViewController.m
//  XYMaterial
//
//  Created by 肖扬 on 15/12/9.
//  Copyright © 2015年 肖扬. All rights reserved.
//

#import "HomeViewController.h"
#import "CycleScrollView.h"
#import "homeVCCell.h"
#import "SUNScrollImage.h"
#import "TitleImageButton.h"
#import "SUNScroll.h"
#import "ASIHTTPRequest.h"
#import "JSONKit.h"
#import "MJRefresh.h"
#import "Animations.h"
#import "DBManage.h"
#import "EGOImageButton.h"
#import "Unity.h"
#import "homeModel.h"
#import "QuickSendViewController.h"
#import "ShopViewController.h"
#import "ProductDetailsViewController.h"
#import "IWantSupplyViewController.h"
#import "IWantPurchaseViewController.h"
#import "BoardViewController.h"
#import "supplyViewButton.h"
#import "TodaySpecialViewController.h"
#import "PopularHistoryView.h"
#import "searchResultListView.h"
#import "MySaveModel.h"
#import "LoginViewController.h"
#import "homeHeadView.h"
#import "DCPicScrollView.h"
@interface HomeViewController ()<MHAsiNetworkDelegate,MJRefreshBaseViewDelegate,historyViewDelegate,searchResultViewDelegate,UIScrollViewDelegate,LoginViewControllerDelegate>{
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    NSMutableArray * _fakeData;
    ASIHTTPRequest *asiHttpRequest;
    PopularHistoryView *hotView;//gao add
    searchResultListView *resultView;
    int Page;
}
@property (nonatomic,strong) homeHeadView *headView;
@end

@implementation HomeViewController
@synthesize firstSearhBar,homeTableView,imageArr,mainScorllView,cellSBtnArray,cellTBtnArray,searchArray,hot_keywords,hotViewArray,headView,mainScorll;
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:YES];
    [[appStatus shareAppStatus].tabBarController showTabbar];//显示底部导航
    UIView *tempNav = (UIView *)[self.navigationController.view viewWithTag:404];
    [tempNav setHidden:NO];
    [self.firstSearhBar setHidden:NO];//设置搜索控件显示
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    UIView *tempNav = (UIView *)[self.navigationController.view viewWithTag:404];
    [tempNav setHidden:YES];
    [self.firstSearhBar setHidden:YES];
}
-(void)drawMainView{
    /**
     *  初始化页面数组
     */
    self.searchArray = [NSMutableArray array];
    self.cellSBtnArray = [NSMutableArray array];
    self.cellTBtnArray = [NSMutableArray array];
    self.imageArr = [NSMutableArray array];
    self.hotViewArray = [NSMutableArray array];
    self.hot_keywords = [NSMutableArray array];
    /**
     初始化搜索控件
     */
    UIView *tempNav = [self createViewFrame:CGRectMake(0, 20, SWIDTH, 44) bgColor:[UIColor clearColor] tag:404];
    [self.navigationController.view addSubview:tempNav];
    
    UISearchBar *tempSearch = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, SWIDTH, 44)];
    self.firstSearhBar = tempSearch;
    self.firstSearhBar.delegate = self;
    self.firstSearhBar.backgroundImage = [self imageWithColor:[UIColor clearColor] size:self.firstSearhBar.bounds.size];
    [self.firstSearhBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"搜索框"] forState:0];
    self.firstSearhBar.placeholder = @"产品";
    [tempNav addSubview:self.firstSearhBar];
    
    for (UIView *view in [[firstSearhBar.subviews lastObject] subviews]) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *cancelBtn = (UIButton *)view;
            [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
    
    // Do any additional setup after loading the view.
    [self setupMainView];
    [self.homeTableView reloadData];
    self.homeTableView.showsHorizontalScrollIndicator = YES;
    self.homeTableView.showsVerticalScrollIndicator = YES;
    //初始化搜索列表
    _tableSearch = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SWIDTH, VHEIGHT)];
    [_tableSearch setBackgroundColor:[UIColor whiteColor]];
    [_tableSearch setDelegate:self];
    [_tableSearch setDataSource:self];
    _tableSearch.separatorStyle = NO;
    [self.mainView addSubview:_tableSearch];
    _tableSearch.hidden = YES;
    [self addHeader];
//    [self addFooter];
}

- (void)setSearchTextFieldBackgroundColor:(UIColor *)backgroundColor
{
    UIView *searchTextField = nil;
     // 经测试, 需要设置barTintColor后, 才能拿到UISearchBarTextField对象
     self.firstSearhBar.barTintColor = UIColorFromRGB(0x246ca7);
//    [self.firstSearhBar setTintColor:[UIColor whiteColor]];
//    searchTextField = [[[self.subviews firstObject] subviews] lastObject];
     searchTextField = [[[self.firstSearhBar.subviews firstObject] subviews] lastObject];
     searchTextField.backgroundColor = backgroundColor;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:UIColorFromRGB(0xf3f2f2)];
    [self drawMainView];
}
- (void)setupMainView{
    //初始化主页面显示
    UITableView *tempTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SWIDTH, VHEIGHT - 44)];
    [tempTableView setBackgroundColor:UIColorFromRGB(0xf3f2f2)];
    [tempTableView setDelegate:self];
    [tempTableView setDataSource:self];
    UIView *theView = [[UIView alloc] initWithFrame:self.mainTableView.frame];
    [theView setBackgroundColor:[UIColor clearColor]];
    self.homeTableView.separatorStyle = NO;
    self.homeTableView = tempTableView;
    self.homeTableView.tag = 836913;
    [self.homeTableView setBackgroundView:theView];
    [self.mainView addSubview:self.homeTableView];
    self.homeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.homeTableView.tableFooterView = [[UIView alloc]init];
}
- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    TIME
    HEADDIC(nowTime, HOME_INDEX);
    NSMutableDictionary *body = [NSMutableDictionary dictionary];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:HEAD forKey:@"head"];
    [dic setObject:body forKey:@"body"];
    /**
     创建请求,result返回请求后的结果
     */
    requestManage *request = [[requestManage alloc]init];
    NSString *result =[request post:APPIP postDataDic:dic error:nil];
    NSLog(@"result___%@",result);
    homeModel *model = [[homeModel alloc]init];
    [model parseResponseData:result];
    
    self.imageArr = [model.data objectForKey:@"banner"];
    self.mainData = [model.data objectForKey:@"supply"];
    self.hot_keywords = [model.data objectForKey:@"hot_keywords"];
    [self.homeTableView reloadData];
    [self.homeTableView flashScrollIndicators];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}
- (void)addFooter
{    __unsafe_unretained HomeViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.homeTableView;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        Page++;
        // 模拟延迟加载数据，因此2秒后才调用）
        // 这里的refreshView其实就是footer
        [vc performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0];
    };
    _footer = footer;
}
- (void)addHeader
{
    __unsafe_unretained HomeViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.homeTableView;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        Page = 1;
        //        [self dataSource:StateURL];
        // 模拟延迟加载数据，因此2秒后才调用）
        // 这里的refreshView其实就是header
        [vc performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0];
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                break;
            case MJRefreshStatePulling:
                break;
            case MJRefreshStateRefreshing:
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

#pragma mark -- 去除searchBar的背景色
//取消searchbar背景色
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == _tableSearch) {
        return 2;
    }else{
        return 1;
    }
}
// 返回每一组有多少行
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _tableSearch) {
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"searchList"]!=nil) {
            if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"searchList"] isKindOfClass:[NSString class]]) {
                return 0;
            }
            self.searchArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"searchList"];
            return [self.searchArray count];
        }
        return 1;
    }
    return self.mainData.count+4;
}

// 返回哪一组的哪一行显示什么内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* cellId = [NSString stringWithFormat:@"cellid%ld",(long)indexPath.row];
    static NSString *tableCell =@"Cell";
    UITableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:tableCell];
    if (tableView == _tableSearch) {
        if (!cell1) {
            cell1 =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableCell];
            [cell1 setSelectionStyle:0];
        }
        if (indexPath.section == 0) {
            if ([self.hotViewArray count]!= 0) {
                for (int i = 0; i < [self.hotViewArray count]; i++) {
                    supplyViewButton *button = [self.hotViewArray objectAtIndex:i];
                    [button removeFromSuperview];
                    button = nil;
                    [self.hotViewArray removeObjectAtIndex:i];
                }
            }
            for (int i = 0; i <[self.hot_keywords count]; i++) {
                tj_brandsModel *brandModel = [self.hot_keywords objectAtIndex:i];
                NSString *nameStr = brandModel.name;
                supplyViewButton *vButton = nil;
                int BtnW = (SWIDTH/3);
                int BtnH = 34;
                vButton = [self returnButtonWithFrame:CGRectMake( BtnW * (i%3) , BtnH *(i/3), BtnW, BtnH ) withTag:i+10 withTitle:nameStr];
                vButton.brand = brandModel;
                [self.hotViewArray addObject:vButton];
                [cell1 addSubview:vButton];
            }
            return cell1;
        }else{
            if (!cell1) {
                cell1 =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableCell];
                [cell1 setSelectionStyle:0];
            }
            if ([self.searchArray count]!=0) {
                cell1.textLabel.text = [self.searchArray objectAtIndex:indexPath.row];
            }
            return cell1;
        }
    }else{
        homeVCCell* cell = (homeVCCell*)[tableView dequeueReusableCellWithIdentifier:cellId];
        
        if(cell == nil){
            cell = [[homeVCCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId] ;
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        if (indexPath.row == 0) {
            if (!cell1) {
                cell1 =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableCell];
                [cell1 setSelectionStyle:0];
                cell1.backgroundColor = [UIColor clearColor];
                }
//            if (!self.headView) {
//                self.headView = [[homeHeadView alloc]initWithFrame:CGRectMake(0, 0, SWIDTH, 390)];
//                [self.headView setHeadView:imageArr];
//                [cell1 addSubview:self.headView];
//            }
            
                NSMutableArray *viewsArray = [@[] mutableCopy];
                for (int c = 0; c < [imageArr count]; c++) {
                    homeModelBanner *banner = [imageArr objectAtIndex:c];
                    SUNScrollImage * temp = [[SUNScrollImage alloc]initWithFrame:CGRectMake(0, 0, SWIDTH, 180)];
                    [temp.imageButton addTarget:self action:@selector(ImgNews:) forControlEvents:UIControlEventTouchUpInside];
                    temp.imageButton.tag = c+30;
                    [temp.imageButton setImageURL:[NSURL URLWithString:banner.image_url]];
                    temp.backgroundColor = [UIColor clearColor];
                    [viewsArray addObject:temp];
                }
                if (self.mainScorllView == nil) {
                    self.mainScorllView = [[CycleScrollView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, 190) animationDuration:2];
                }
                self.mainScorllView.backgroundColor = [[UIColor clearColor] colorWithAlphaComponent:0];
                self.mainScorllView.fetchContentViewAtIndex = ^UIView *(NSInteger pageIndex){
                    return viewsArray[pageIndex];
                };
                self.mainScorllView.totalPagesCount = ^NSInteger(void){
                    return [viewsArray count];
                };
                self.mainScorllView.TapActionBlock = ^(NSInteger pageIndex){
                };
                cell1.contentView.backgroundColor = [UIColor clearColor];
                [cell1 addSubview:self.mainScorllView];
            
                return cell1;
        }else if (indexPath.row == 1){
            if (!cell1) {
                cell1 =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableCell];
                [cell1 setSelectionStyle:0];
                cell1.backgroundColor = [UIColor whiteColor];
            }
            NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"我要采购",@"我要供货",@"今日特价",@"直销商城",@"快速发布", nil];
            NSMutableArray *imgArr = [NSMutableArray arrayWithObjects:@"我要采购-拷贝",@"我要供货",@"今日特价",@"直销商城",@"快速发布", nil];
            int w = SWIDTH/5;
            int h = 75;
            if ([self.cellSBtnArray count]!=0) {
                for (int k = 0; k < [self.cellSBtnArray count]; k++) {
                    TitleImageButton *button = [self.cellSBtnArray objectAtIndex:k];
                    [button removeFromSuperview];
                    button = nil;
                }
                [self.cellSBtnArray removeAllObjects];
            }
            for (int i = 0; i < [arr count]; i++) {
                TitleImageButton*btn=[TitleImageButton createBtnFrame:CGRectMake(w*i, 10, w, h) title:arr[i] imageName:imgArr[i] selecetdImage:@"" titleColor:[UIColor blackColor] target:self action:@selector(clickThisBtn:) style:TitleImageButtonDistributeStyleImageTopAndBottom tag:100+i];
                btn.textAlignment=NSTextAlignmentCenter;
                btn.imageMode=UIViewContentModeTop;
                btn.imageRatio=0.6;
                btn.titleLabel.font = [UIFont systemFontOfSize:12];
                [self.cellSBtnArray addObject:btn];
                [cell1 addSubview:btn];
            }
            return cell1;
        }else if (indexPath.row == 2){
            if (!cell1) {
                cell1 =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableCell];
                [cell1 setSelectionStyle:0];
                cell1.backgroundColor = [UIColor clearColor];
            }
            if ([self.cellTBtnArray count]!=0) {
                for (UIView *view in self.cellTBtnArray) {
                    [view removeFromSuperview];
                }
                [self.cellTBtnArray removeAllObjects];
            }
            int w = SWIDTH/3;
            int h = 10;
            int bw = SWIDTH/3-20;
            int bh = 70;
            UIView *tempView2 =[[UIView alloc]initWithFrame:CGRectMake(0, 10, SWIDTH, 90)];
            tempView2.backgroundColor = [UIColor whiteColor];
            [self.cellTBtnArray addObject:tempView2];
            [cell1 addSubview:tempView2];
            for (int i = 0; i < 3; i++) {
                UIButton *button = [self createButtonFrame:CGRectZero title:@"" viewController:self selector:@selector(home3Clcik:) tag:i+10];
                UIView *view = nil;
                if (i == 0) {
                    button.frame = CGRectMake(10, h, bw, bh);
                    [button setBackgroundImage:[UIImage imageNamed:@"板材背景"] forState:0];
                    view= [self returnView:CGRectMake(0, 0, bw, bh) ImageView:25 height:25 image:@"首页-板材" title:@"板材" tag:i+10];
                }
                if (i == 1) {
                    button.frame = CGRectMake(w+10, h, bw, bh);
                    [button setBackgroundImage:[UIImage imageNamed:@"门板背景"] forState:0];
                    view = [self returnView:CGRectMake(0, 0, bw, bh) ImageView:15 height:26 image:@"首页-门板" title:@"门板" tag:i+10];
                }
                if (i == 2) {
                    button.frame = CGRectMake(w*2+10, h, bw, bh);
                    [button setBackgroundImage:[UIImage imageNamed:@"装饰纸背景"] forState:0];
                    view = [self returnView:CGRectMake(0, 0, bw, bh) ImageView:26 height:26 image:@"首页-装饰纸" title:@"装饰纸" tag:i+10];
                }
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)]; 
                [view addGestureRecognizer:tap];
                [button addSubview:view];
                [tempView2 addSubview:button];
            }
            cell1.backgroundView.backgroundColor = [UIColor clearColor];
            cell1.contentView.backgroundColor = [UIColor clearColor];
            return cell1;
        }else if (indexPath.row == 3){
            if (!cell1) {
                cell1 =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableCell];
                [cell1 setSelectionStyle:0];
                cell1.backgroundColor = [UIColor whiteColor];
                
                UILabel *lab = [self createLabelFrame:CGRectMake(10, 10, SWIDTH - 20, 10) title:@"特价推荐" titleColor:BLACKColor tag:0];
                lab.font = [UIFont systemFontOfSize:12];
                [cell1 addSubview:lab];
            }
            return cell1;
        }else{
            homeModelSupply *supply = [self.mainData objectAtIndex:indexPath.row - 4];
            [cell drawCellView:supply];
            return cell;
        }
    }
}
-(UIView *)returnView:(CGRect)frame
        ImageView:(int)width
            height:(int)height
             image:(NSString *)image
             title:(NSString *)title
              tag:(int)tag{
    UIView *view = [self createViewFrame:frame bgColor:[UIColor clearColor] tag:0];
    view.tag = tag;
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake((view.frame.size.width - width)/2, (view.frame.size.height-height)/2, width, height)];
    imageV.image = [UIImage imageNamed:image];
    [imageV setBackgroundColor:[UIColor clearColor]];
    [view addSubview:imageV];
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(0, view.frame.size.height - 20, view.frame.size.width, 11)];
    lab.textColor = [UIColor whiteColor];
    lab.backgroundColor = [UIColor clearColor];
    lab.font = [UIFont systemFontOfSize:11];
    lab.text = title;
    lab.textAlignment = NSTextAlignmentCenter;
    [view addSubview:lab];
    return view;
}

-(void)ImgNews:(EGOImageButton *)sender{
    homeModelBanner *banner = [imageArr objectAtIndex:sender.tag - 30];
    if (banner.link_url!=nil && ![banner.link_url isEqualToString:@""]) {
        NSLog(@"link_url___%@",banner.link_url);
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:banner.link_url]];
    }
}
-(supplyViewButton *)returnButtonWithFrame:(CGRect)frame  withTag:(int)Tag withTitle:(NSString *)title{
    supplyViewButton *vButton = [[supplyViewButton alloc]initWithFrame:frame];
    [vButton.button setTitle:title forState:0];
    [vButton.button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [vButton.button setFrame:CGRectMake((frame.size.width - 70)/2, 0, 70, 24)];
    vButton.button.titleLabel.font = [UIFont systemFontOfSize:12];
    [vButton.button setTitleColor:UIColorFromRGB(0x2578c3) forState:UIControlStateSelected];
    [vButton.button setBackgroundColor:[UIColor clearColor]];
    Radio(vButton.button, grayColor);
    [vButton.button setSelected:NO];
    [vButton.button addTarget:self action:@selector(selectCity:) forControlEvents:UIControlEventTouchUpInside];
    return vButton;
}
-(void)selectCity:(UIButton *)sender{
    
}
-(void)clickThisBtn:(TitleImageButton *)sender{
    //TODO: 按钮点击
    TABHIDDEN
    if (sender.tag == 100) {
        IWantPurchaseViewController *purchaseVC = [[IWantPurchaseViewController alloc]init];
        purchaseVC.title = @"我要采购";
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"0"] || [[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] == nil) {
            LoginViewController *loginVC = [[LoginViewController alloc]init];
            loginVC.title = @"登录";
            loginVC.baseVC = purchaseVC;
            loginVC.delegate = self;
//            [self.navigationController pushViewController:loginVC animated:YES];
            [self presentViewController:loginVC animated:YES completion:^{
                loginVC.viewState = 1;
            }];
            return;
        }
        [self.navigationController pushViewController:purchaseVC animated:YES];
    }else if (sender.tag == 101){
        IWantPurchaseViewController *purchaseVC = [[IWantPurchaseViewController alloc]init];
        purchaseVC.title = @"我要供货";
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"0"] || [[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] == nil) {
            LoginViewController *loginVC = [[LoginViewController alloc]init];
            loginVC.title = @"登录";
            loginVC.baseVC = purchaseVC;
            loginVC.delegate = self;
//            [self.navigationController pushViewController:loginVC animated:YES];
            [self presentViewController:loginVC animated:YES completion:^{
                loginVC.viewState = 1;
            }];
            return;
        }
        [self.navigationController pushViewController:purchaseVC animated:YES];
    }else if (sender.tag == 102){
        ShopViewController *shopVC = [[ShopViewController alloc]init];
        shopVC.title = @"今日特价";
        shopVC.viewUrl = SALESGETLIST;
        [self.navigationController pushViewController:shopVC animated:YES];
    }else if (sender.tag == 103){
        ShopViewController *shopVC = [[ShopViewController alloc]init];
        shopVC.title = @"直销商城";
        shopVC.viewUrl = SHOPGETLIST;
        [self.navigationController pushViewController:shopVC animated:YES];
    }else{
        QuickSendViewController *quickVC = [[QuickSendViewController alloc]init];
        quickVC.title = @"快速发布";
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"0"] || [[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] == nil) {
            LoginViewController *loginVC = [[LoginViewController alloc]init];
            loginVC.title = @"登录";
            loginVC.baseVC = quickVC;
            loginVC.delegate = self;
//            [self.navigationController pushViewController:loginVC animated:YES];
            [self presentViewController:loginVC animated:YES completion:^{
                loginVC.viewState = 1;
            }];
            return;
        }
        [self.navigationController pushViewController:quickVC animated:YES];
    }
}
-(void)pushToNextViewController:(id)viewController{
    BaseViewController *baseVC = (BaseViewController *)viewController;
    [self.navigationController pushViewController:baseVC animated:YES];
}
-(void)tapClick:(UITapGestureRecognizer *)tap{
    UIButton *button = (UIButton *)[self.view viewWithTag:tap.view.tag];
    [self home3Clcik:button];
}
-(void)home3Clcik:(UIButton *)sender{
    TABHIDDEN
    BoardViewController *boardVC = [[BoardViewController alloc]init];
    boardVC.type = sender.tag - 10;
    switch (sender.tag) {
        case 10:
            boardVC.title = @"板材";
            break;
        case 11:
            boardVC.title = @"门板";
            break;
        case 12:
            boardVC.title = @"装饰纸";
            break;
        default:
            break;
    }
    boardVC.viewUrl = SUPPLYLIST;
    [self.navigationController pushViewController:boardVC animated:YES];
}

//显示搜索框
- (void)showSearchBar {
    TABHIDDEN//隐藏tabbar 否则会多出44像素高度
    [firstSearhBar setShowsCancelButton:YES animated:YES];
    firstSearhBar.placeholder = @"请输入...";
    [self hotHistory];//gao add

}
//隐藏搜索框
- (void)disapperSearchBar:(NSInteger)actionType {
    [firstSearhBar setShowsCancelButton:NO animated:YES];
    firstSearhBar.placeholder = @"产品";
    switch (actionType) {
        case 0://Cancel按钮
//            firstSearhBar.text = _currentSearchName;
            //设置保存的列表
            _tableSearch.hidden = YES;
            if (!_tableSearch.hidden) {
                [_tableSearch reloadData];
            }
            break;
        case 1://Search按钮
        {
            if (firstSearhBar.text.length >0) {
                //非空值搜索
                [self saveHistoryText:self.firstSearhBar.text];
            } else {
                //空值搜索
                SHOW_ALERT(@"请输入搜索的内容");
                return;
            }
            
        }
            break;
        default:
            break;
            
    }
    [firstSearhBar resignFirstResponder];
    [[appStatus shareAppStatus].tabBarController showTabbar];
}
-(void)saveHistoryText:(NSString *)text{
    NSMutableArray * arr = [NSMutableArray array];
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"searchList"]!=nil) {
        if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"searchList"] isKindOfClass:[NSString class]]) {
            NSMutableArray *arr1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"searchList"];
            [arr addObjectsFromArray:arr1];
        }
    }
    [arr addObject:text];
    self.searchArray = arr;
    [[NSUserDefaults standardUserDefaults] setObject:arr forKey:@"searchList"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
#define WS(weakSelf)  __weak __typeof(&*self)weakSelf = self;
-(void)clearHisView{
    [hotView removeFromSuperview];
    hotView = nil;
    WS(wself);
    if(!hotView){
        hotView = [[PopularHistoryView alloc]init];
        hotView.frame = CGRectMake(0, 0, SWIDTH, VHEIGHT);
        hotView.backgroundColor = [UIColor whiteColor];
        hotView.delegate = self;
        hotView.h_block = ^(NSString *text,NSInteger index){
            wself.firstSearhBar.text = text;
            [wself saveHistoryText:text];
            [wself hot_keyword:text];
        };
        [self.mainView addSubview:hotView];
    }
}
-(void)pushDetailsVC:(id)obj{
    homeModelSupply *supply = (homeModelSupply *)obj;
    ProductDetailsViewController *productDetailsVC = [[ProductDetailsViewController alloc]init];
    productDetailsVC.supply = supply;
    [self.navigationController pushViewController:productDetailsVC animated:YES];
}
//进入历史界面
-(void)hotHistory{
    WS(wself);
    self.firstSearhBar.text = @"";
    [resultView removeFromSuperview];
    resultView = nil;
    if(!hotView){
        hotView = [[PopularHistoryView alloc]init];
        hotView.frame = CGRectMake(0, 0, SWIDTH, VHEIGHT);
        hotView.backgroundColor = [UIColor whiteColor];
        hotView.delegate = self;
        hotView.h_block = ^(NSString *text,NSInteger index){
            wself.firstSearhBar.text = text;
            [wself saveHistoryText:text];
            [wself hot_keyword:text];
        };
        [self.mainView addSubview:hotView];
    }
    
}
-(void)hot_keyword:(id)obj{
    self.firstSearhBar.text = obj;
    TIME
    HEADDIC(nowTime, SEARCHLIST);
    NSMutableDictionary *body = [NSMutableDictionary dictionary];
    [body setObject:obj forKey:@"keyword"];
    [body setObject:[NSNumber numberWithInt:1] forKey:@"page"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:HEAD forKey:@"head"];
    [dic setObject:body forKey:@"body"];
    requestManage *request = [[requestManage alloc]init];
    NSString *result = [request post:APPIP postDataDic:dic error:nil];
    NSLog(@"result__%@",result);
    MySaveModel *model = [[MySaveModel alloc]init];
    [model parseResponseData:result];
    [self resultListView:model.list];
}
//进入结果页面
-(void)resultListView:(NSMutableArray *)list{
    [hotView removeFromSuperview];
    hotView = nil;
    [firstSearhBar resignFirstResponder];
    if(!resultView){
        resultView = [[searchResultListView alloc]init];
        resultView.hisList = list;
        resultView.text = self.firstSearhBar.text;
        resultView.frame = CGRectMake(0, 0, SWIDTH, VHEIGHT);
        resultView.backgroundColor = [UIColor whiteColor];
        resultView.delegate = self;
        [self.mainView addSubview:resultView];
        [resultView makeSeachData:list];
    }
    
    
}

#pragma mark - UISearchBar Delegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setTintColor:[UIColor whiteColor]];
    for (UIView *view in [[searchBar.subviews lastObject] subviews]) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *cancelBtn = (UIButton *)view;
            [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
            [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    // return NO to not become first responder
    [self showSearchBar];
    return YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    //超过20位后截取前20位
    if (searchText.length > 20) {
        firstSearhBar.text = [searchText substringToIndex:20];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    // called when keyboard search button pressed
    [self disapperSearchBar:1];
    [firstSearhBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    // called when cancel button pressed
    [hotView removeFromSuperview];
    hotView = nil;
    [self disapperSearchBar:0];
    [firstSearhBar resignFirstResponder];
}

#pragma mark - UITableViewDelegate
// 当每一行的cell的高度不一致的时候就使用代理方法设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableSearch) {
        if (indexPath.section == 0) {
            int height = 0;
            for (int i = 0; i <[self.hotViewArray count]; i++) {
                tj_brandsModel *brandModel = [self.hotViewArray objectAtIndex:i];
                NSString *nameStr = brandModel.name;
                supplyViewButton *vButton = nil;
                int BtnW = (SWIDTH/3);
                int BtnH = 34;
                vButton = [self returnButtonWithFrame:CGRectMake( BtnW * (i%3) , BtnH *(i/3), BtnW, BtnH ) withTag:i+10 withTitle:nameStr];
                vButton.brand = brandModel;
                height = BtnH *(i/3) + 50;
            }
            return height;
        }else{
            return 44;
        }
    }else{
        if (0 == indexPath.row) {
         return 192;
        }
        else if (1 == indexPath.row){
         return 88;
        }
        else if (2 == indexPath.row){
         return 110;
        }else if (3 == indexPath.row){
            return 20;
        }
        return 104;
    }
    return 0;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableSearch) {
        firstSearhBar.placeholder = @"产品";
        [self disapperSearchBar:0];
    }else{
        if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 3) {
            NSLog(@"无操作");
            return;
        }
        TABHIDDEN
        ProductDetailsViewController *productDetailsVC = [[ProductDetailsViewController alloc]init];
        productDetailsVC.supply = [self.mainData objectAtIndex:indexPath.row -4];
        [self.navigationController pushViewController:productDetailsVC animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
